﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 作者: Foldcc
/// QQ: 1813547935
/// 玩家控制器
/// </summary>
public class PlayerController : MonoBehaviour {
	// 自己的金币颜色
	public int coinColor;
	public int playerIdx;

    public Vector2 moveDirection;


    //玩家的各类基础属性，直接取即可
    public PlayerStatus playerStatus;

    public bool holdingCoin;

	
	private int score;
	private ArrayList m_inRangeCoins = new ArrayList();
	private GameObject m_pickCoin = null;
	private Rigidbody2D rb2D;
	private Animator playerAnimator;
	private SpriteRenderer spriteRender;
	public float m_speed;
	private bool m_inRecycle;
	private bool m_dig=false;
	private Vector2 m_moveDir;
	private bool m_fly=false;
	private GameObject m_digCoin = null;
	private bool m_isDizzy = false;

	
	void Start() {
        playerStatus = GetComponent<PlayerStatus>();
		rb2D = GetComponent<Rigidbody2D>();
		playerAnimator = GetComponent<Animator> ();
		spriteRender = GetComponent<SpriteRenderer>();
	}
	void FixedUpdate() {
	}

	void Update(){
    }

	//主角初始化
    public void initPlayer(float speedValue){
		m_speed = speedValue;
        
		UIController.playerHp = 0;
	}

	//碰撞检测
	void OnTriggerEnter2D(Collider2D other){
		// 处理金币
		if (other.gameObject.CompareTag("Coin")) {
			m_inRangeCoins.Add(other.gameObject);
		} else if (other.gameObject.CompareTag("Recycle")){
			m_inRecycle = true;
		}
	}

	private void OnTriggerExit2D(Collider2D other) {
		if (other.gameObject.CompareTag("Coin")) {
			m_inRangeCoins.Remove(other.gameObject);
		} else if (other.gameObject.CompareTag("Recycle")){
			m_inRecycle = false;
		}
	}

	private void OnCollisionEnter2D(Collision2D other) {
		if (m_fly && other.gameObject.CompareTag("Player")){
			other.gameObject.GetComponent<PlayerController>().SetDizzy(true);
		}
	}

	// 扔掉coin
	public void DropCoin(){
		if (m_pickCoin == null){
			return;
		}
		var coinAI = m_pickCoin.GetComponent<CoinAI>();
		Debug.Log(coinAI.coinColor.ToString() + " : " + coinColor.ToString());
		coinAI.onDropingCoin();
		if (m_inRecycle && coinAI.coinColor == coinColor){
			AddScore(1);
			Destroy(m_pickCoin);
		} else {
			m_pickCoin.transform.parent = null;
			m_pickCoin = null;
		}
        //扔掉coin以后就不扣耐力了
        holdingCoin = false;
		playerAnimator.SetBool("hold", false);
		Debug.Log("drop coin");
	}

	private bool CanMove(){
		return !(m_dig || m_fly || m_isDizzy);
	}
    
	public void PickCoin(){
		if (m_inRangeCoins.Count == 0 || m_pickCoin != null || !CanMove()){
			return;
		}
		GameObject nearestCoin = GetNearestCoin();
		if (nearestCoin != null){
			var coinAI = nearestCoin.GetComponent<CoinAI>();
			if(coinAI.canHoldCoin()){
				OnDigCoin(nearestCoin);
			}else{
				StartCoroutine(startDig(nearestCoin));
			}
		}
	}

	public void OnDigCoin(GameObject coin){
		//记录一下拿着coin的状态，拿着coin的时候要持续扣耐力
		holdingCoin = true;
		m_pickCoin = coin;
		m_pickCoin.transform.parent = transform;
		m_pickCoin.transform.localPosition = new Vector3(0.1f, 0.1f, 0);
		var coinAI1 = m_pickCoin.GetComponent<CoinAI>();
		coinAI1.onHoldingCoin();
		playerAnimator.SetBool("hold", true);
		Debug.Log("pick coin success");
	}

	IEnumerator startDig(GameObject coin){
		m_dig = true;
		m_digCoin = coin;
		playerAnimator.SetBool("dig", true);
		yield return new WaitForSeconds(Const.digTime);
		m_dig = false;
		playerAnimator.SetBool("dig", false);
		GameObject nearestCoin = GetNearestCoin();
		if (nearestCoin == m_digCoin){
			OnDigCoin(m_digCoin);
			foreach (GameObject eachCoin in m_inRangeCoins){
				if (eachCoin != nearestCoin)
					eachCoin.GetComponent<CoinAI>().onDiggingOut();
			}
		}
		m_digCoin = null;
	}

	private GameObject GetNearestCoin(){
		// 找到最近的coin
		GameObject nearestCoin = null;
		float minDist = 1000000000;
		foreach(GameObject coinGO in m_inRangeCoins){
			float dist = Vector3.Distance(transform.position, coinGO.transform.position);
			if (dist < minDist){
				minDist = dist;
				nearestCoin = coinGO;
			}
		}
		return nearestCoin;
	}

    public void CastSkill()
    {
        GetComponent<SkillBase>().Cast();
    }

	private void AddScore(int _score){
		score += _score;
		GameObject.FindGameObjectWithTag("MainCamera").GetComponent<UIController>().SetScore(playerIdx, score);
	}

	//玩家移动方法
	void OnMove(Vector2 move) {
		if (!CanMove())
			return;

        moveDirection = move.normalized;
		move.Normalize();

		playerAnimator.SetBool("run", (Mathf.Abs(move.x) > 0.1 || Mathf.Abs(move.y) > 0.1));
		spriteRender.flipX = move.x < 0;
		
        float _speed;
		if (m_pickCoin != null){
			_speed = m_speed / 2.0f;
		}else{
			_speed = m_speed;
		}
		m_moveDir = move;
        rb2D.MovePosition((Vector2)transform.position + m_moveDir * _speed * Time.deltaTime);
    }

	void FlyForward(){
		if (!CanMove())
			return;
		StartCoroutine(StartFly());
	}

	IEnumerator StartFly(){
		m_fly = true;
		float start = Time.time;
		playerAnimator.SetBool("fly", true);
		while (Time.time - start < Const.flyTime){
			rb2D.MovePosition((Vector2)transform.position + m_moveDir * m_speed * Time.deltaTime);
			yield return null;
		}
		playerAnimator.SetBool("fly", false);
		m_fly = false;
	}

	void SetDizzy(bool isDizzy){
		m_isDizzy = isDizzy;

		StopCoroutine("DizzyCoro");
        StartCoroutine("DizzyCoro"); 
	}

	IEnumerator DizzyCoro(){
		yield return new WaitForSeconds(Const.dizzyTime);
		m_isDizzy = false;
	}
}
